var express = require('express');
var router = express.Router();
let jwt = require('jsonwebtoken');
let multiparty = require('multiparty');
let {
  userModel,
  houseModel,
  friendModel,
  messageModel,
} = require('../model/model');

// 获取对话列表
router.get('/getFriendList', async (req, res) => {
  let { _id } = req.query;
  let friendList = await friendModel
    .find({ usersid: { $in: [_id] } })
    .populate('usersid');
  res.status(200).send({
    message: 'success',
    data: friendList,
    code: 200,
  });
});

// 获取聊天信息
router.get('/getMessageList', async (req, res) => {
  let { _id } = req.query;
  // 查找与 friendid 匹配的数据，按时间戳倒序排列，限制返回 10 条数据
  let messageList = await messageModel
    .find({ friendid: _id })
    .sort({ time: -1 }) // 按照创建时间倒序排序
    .limit(20); // 限制返回 10 条数据

  // 将结果反转，以保持消息的顺序（最早的在前）
  messageList = messageList.reverse();

  res.status(200).send({
    message: 'success',
    data: messageList,
    code: 200,
  });
});

// 获取用户
router.get('/getUserInfo', async (req, res) => {
  let { _id } = req.query;
  let user = await userModel.findOne({ _id });
  res.status(200).send({
    message: 'success',
    data: user,
    code: 200,
  });
});

// 添加聊天记录
router.post('/addMessage', async (req, res) => {
  let content = req.body;
  await messageModel.create(content);
  let friendid = content.friendid;
  let message = content.content;
  if (content.type === 0) {
    message = content.content;
  } else if (content.type === 1) {
    message = '[图片]';
  } else {
    message = '[视频]';
  }
  // BUG 怎么做到朋友信息的实时更新。。重新获取数据吗？
  await friendModel.updateOne(
    { _id: friendid },
    { $set: { content: message, time: Date.now() } }
  );
  res.status(200).send({
    message: 'success',
    data: null,
    code: 200,
  });
});
module.exports = router;
